<?php

namespace app\services\distributor;

use app\dao\distributor\DistributorDao;
use app\model\distributor\Distributor;
use app\services\BaseServices;
use crmeb\exceptions\AdminException;

class DistributorService extends BaseServices
{
    public function __construct(DistributorDao $dao)
    {
        $this->dao = $dao;
    }

    public function getList(array $where)
    {
        [$page, $limit] = $this->getPageValue();
        $page = $page == 0 ? 1 : $page;
        return $this->dao->getList($where, $page, $limit);
    }


    public function save($id, $data)
    {
        if (!isset($data['distributor_name']) || $data['distributor_name'] == '') throw new AdminException(30017);
        if (!isset($data['contact_person']) || $data['contact_person'] == '') throw new AdminException(30018);
        if (!isset($data['contact_info']) || $data['contact_info'] == '') throw new AdminException(30019);
        if (!isset($data['responsible_area']) || $data['responsible_area'] == '') throw new AdminException(30020);

        if ($id) {
            $res = $this->dao->update($id, $data);
            if (!$res) throw new AdminException(10022);
        } else {

            // 判断不能为重复值
            $count = Distributor::where('contact_info', $data['contact_info'])->count();
            if ($count) throw new AdminException(30021);

            $data['status'] = 1;
            $data['add_time'] = time();
            $data['create_method'] = 1;
            $res = $this->dao->save($data);
            if (!$res) throw new AdminException(10022);
        }
    }


    public function setStatus(array $ids, int $is_show)
    {
        if (empty($ids)) throw new AdminException(100100);
        $this->dao->batchUpdate($ids, ['status' => $is_show]);
        return true;
    }

    public function all()
    {
        return $this->dao->all()->toArray();
    }
}